package com.alibaba.cloud.base.business.user.controller;

import com.alibaba.cloud.base.business.user.domain.LoginUser;
import com.alibaba.cloud.base.business.user.service.LoginUserService;
import com.alibaba.framework.aop.log.LogWrite;
import com.alibaba.framework.domain.ResponseWrapper;
import com.alibaba.framework.exception.ResponseCode;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Tag(name = "用户模块")
@RestController
@RequestMapping("/user")
public class LoginUserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginUserController.class);

    @Resource
    private LoginUserService userService;

//    @SentinelResource("getByUserId")
    @LogWrite(value = "根据userId查询用户")
    @GetMapping("/get/{userId}")
    public ResponseWrapper getLoginUser(@PathVariable("userId") String userId) {

//        initFlowRules();

        /*while (true) {
            // 1.5.0 版本开始可以直接利用 try-with-resources 特性
            try (Entry entry = SphU.entry("getByUserId")) {
                // 被保护的逻辑
                LoginUser loginUser = userService.getLoginUser(userId);
                System.out.println("被保护的逻辑: hello world");

                return ResponseWrapper.Success(loginUser);
            } catch (BlockException ex) {
                // 处理被流控的逻辑
                System.out.println(">>>>>>>>>>>>>>>处理被流控的逻辑: blocked!<<<<<<<<<<<<<<<<<<");
            }
        }*/

        LoginUser loginUser = userService.getLoginUser(userId);
        return ResponseWrapper.Success(loginUser);
    }

    /*private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("getByUserId");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }*/

    @LogWrite(value = "新用户注册")
    @PostMapping("/registerUser")
    public ResponseWrapper registerLoginUser(@RequestBody LoginUser user) {

        userService.registerLoginUser(user);
        return ResponseWrapper.Success();
    }

    @LogWrite(value = "用户登录")
    @PostMapping("/login")
    public ResponseWrapper login(@RequestBody LoginUser user) {

        ResponseWrapper wrapper = userService.login(user);
        if (ResponseCode.SUCCESS_CODE == wrapper.getCode()) {
            return ResponseWrapper.Success("登录成功", wrapper.getData());
        } else {
            return ResponseWrapper.Fail(wrapper.getMessage());
        }
    }

    @LogWrite(value = "用户注销")
    @PostMapping("/logout")
    public ResponseWrapper logoutUser(@RequestParam("userId") String userId) {

        Boolean boo = userService.logoutUser(userId);
        return boo ? ResponseWrapper.Success() : ResponseWrapper.Fail();
    }
}
